package com.guchenbo.example.sasl;

import javax.security.auth.callback.*;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class ClientSaslExample {
    public static void main(String[] args) {
        try {
            // 客户端提供的用户名和密码
            String username = "myUser";
            String password = "myPassword";

            String mechanism = "PLAIN"; // 选择SASL机制
            String protocol = "example"; // 使用的协议
            String serverName = "myServer"; // 服务器名

            // 创建客户端回调处理程序
            CallbackHandler callbackHandler = new CallbackHandler() {
                @Override
                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                    for (Callback callback : callbacks) {
                        if (callback instanceof NameCallback) {
                            NameCallback nameCallback = (NameCallback) callback;
                            nameCallback.setName(username);
                        } else if (callback instanceof PasswordCallback) {
                            PasswordCallback passwordCallback = (PasswordCallback) callback;
                            passwordCallback.setPassword(password.toCharArray());
                        } else {
                            throw new UnsupportedCallbackException(callback, "Unsupported Callback");
                        }
                    }
                }
            };

            Map<String, String> props = new HashMap<>();
            props.put(Sasl.QOP, "auth"); // SASL质量保证参数

            SaslClient saslClient = Sasl.createSaslClient(new String[]{mechanism}, null, protocol, serverName, props, callbackHandler);

            // 获取客户端响应
            byte[] clientResponse = saslClient.evaluateChallenge(new byte[0]);

            // 将客户端响应发送给服务器
            // 假设服务器的挑战为 challenge

            // 服务器挑战的处理
            byte[] challenge = "hello".getBytes(StandardCharsets.UTF_8); // 服务器挑战

            // 客户端再次处理服务器的挑战
            byte[] clientResponse2 = saslClient.evaluateChallenge(challenge);

            if (saslClient.isComplete()) {
                System.out.println("认证成功");
            } else {
                System.out.println("认证失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

